﻿import de.back2dos.as24x.xXML;
import de.back2dos.as24x.xXMLError;
/**
 * pendant of AS3's XMLList. only interesting thing about it is the filter function, which is the closest to .(<expr>) filtering you can get
 * will behave like xXML otherwise
 */
dynamic class de.back2dos.as24x.xXMLList {	
	private var _entries:Array;
	private function xXMLList(entries:Array) {
		this._entries = entries;
	}
	public function get length():Number { return this._entries.length };
	/**
	 * will filter the list using a filter Function
	 * @param	filter a Function of type function (item:xXML):Boolean
	 * @return
	 */
	public function filter(filter:Function):xXMLList {
		var children:Array = this._entries;
		var length:Number = children.length;
		var ret:Array = [];
		var x:xXML;
		for (var i:Number = 0; i < length; i++) if (filter(x = children[i])) ret.push(x);
		return xXMLList.create(ret);
	}
	private function __resolve(prop:String):Object {
		if (parseFloat(prop) % 1 == 0) return this._entries[prop];
		if (prop.charAt(0) == "$") {
			if (this.length != 1) xXMLError.fire("attributes may only be read from lists with length 1");
			return this._entries[0]._attributes[prop.substr(1)];
		}
		if (prop.substr(0, 4) == "set$") {
			if (this.length != 1) xXMLError.fire("attributes may only be written to lists with length 1");
			var attr:Object = this._entries[0]._attributes;
			prop = prop.substr(4);
			return function (value:Object):Object { return attr[prop] = value; }
		}
		return this.filter(function (x:xXML):Boolean { return x.nodeName == prop };);
	}
	public function toString():String {
		return "[object xXMLList]";
	}
	private static function create(entries:Array):xXMLList {
		var ret = function () { xXMLError.fire("call to non function object xXMLList") };
		var constr = xXMLList;
		ret.__proto__ = constr.prototype;
		constr.call(ret, entries);
		return ret;
	}
}